import Message from 'element-ui/packages/message/src/main';
import CryptoJS from 'crypto-js'

export function checkStatus(res, successText, failText) {
  if (res.meta.status >= 300) {
    Message.warning(failText || res.meta.msg);
    return false;
  }
  Message.success(successText || res.meta.msg);
  return true;
}

export function getUrlKey(name, url) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ''])[1].replace(/\+/g, '%20')) || null;
}

export function timeFormat(time,format="yyyy-MM-dd hh:mm:ss") {
  let date = new Date(time);
  let year = '0' + date.getFullYear();
  let month = '0' + (date.getMonth()+1);
  let day = '0' + date.getDate();
  let hour = '0' + date.getHours();
  let minute = '0' + date.getMinutes();
  let second = '0' + date.getSeconds();
  if(format.includes('y')) {
    format = format.replace(/y+/,year.slice(-(format.match(/y+/)[0].length)));
  }
  if(format.includes('M')) {
    format = format.replace(/M+/,month.slice(-(format.match(/M+/)[0].length)));
  }
  if(format.includes('d')) {
    format = format.replace(/d+/,day.slice(-(format.match(/d+/)[0].length)));
  }
  if(format.includes('h')) {
    format = format.replace(/h+/,hour.slice(-(format.match(/h+/)[0].length)));
  }
  if(format.includes('m')) {
    format = format.replace(/m+/,minute.slice(-(format.match(/m+/)[0].length)));
  }
  if(format.includes('s')) {
    format = format.replace(/s+/,second.slice(-(format.match(/s+/)[0].length)));
  }
  return format;
}

export function debounce(fn, delay, isImmediate) {
  var timer = null;  //初始化timer，作为计时清除依据
  return function () {
    var context = this;  //获取函数所在作用域this
    var args = arguments;  //取得传入参数
    if (timer) clearTimeout(timer);
    if (isImmediate && timer === null) {
      //时间间隔外立即执行
      fn.apply(context, args);
      timer = 0;
    } else {
      timer = setTimeout(function () {
        fn.apply(context, args);
        timer = null;
      }, delay);
    }
  };
}
